package com.WOWTradeNews.phone;


import java.util.HashSet;
import java.util.Locale;
import java.util.Set;



import com.WOWTradeNews.Billing.PurchaseDatabase;
import com.WOWTradeNews.Billing.ResponseHandler;

import com.WOWTradeNews.Billing.Consts;
import com.WOWTradeNews.Billing.PurchaseObserver;
import com.WOWTradeNews.Billing.BillingService.RequestPurchase;
import com.WOWTradeNews.Billing.Consts.ResponseCode;


import com.WOWTradeNews.Billing.*;
import com.WOWTradeNews.Billing.BillingService.RestoreTransactions;
import com.WOWTradeNews.Billing.Consts.PurchaseState;
import com.WOWTradeNews.DataBase.ConstValues;
import com.WOWTradeNews.DataBase.DBManager;
import com.WOWTradeNews.DataBase.SystemDBManager;
import com.WOWTradeNewsTest.R;
import com.WOWTradeNewsTest.R.color;
import com.WOWTradeNews.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.Toast;

public class Billing extends Activity implements android.view.View.OnClickListener{
	private Button bill;
	private int checkType;
	private Button backButton;
	
	/////////////
	private static final String TAG = "Dungeons";
	private BillingService mBillingService;
	
	private DungeonsPurchaseObserver mDungeonsPurchaseObserver;
	private PurchaseDatabase mPurchaseDatabase;
	private Handler mHandler;
	
	private static final int DIALOG_CANNOT_CONNECT_ID = 1;
    private static final int DIALOG_BILLING_NOT_SUPPORTED_ID = 2;
    
    /**
     * Used for storing the log text.
     */
    private static final String LOG_TEXT_KEY = "DUNGEONS_LOG_TEXT";

    /**
     * The SharedPreferences key for recording whether we initialized the
     * database.  If false, then we perform a RestoreTransactions request
     * to get all the purchases for this user.
     */
    private static final String DB_INITIALIZED = "db_initialized";
    
    
	/**
     * The developer payload that is sent with subsequent
     * purchase requests.
     */
    private String mPayloadContents = null;
	
    
    /**
     * Called when this activity becomes visible.
     */
    @Override
    protected void onStart() {
        super.onStart();
        ResponseHandler.register(mDungeonsPurchaseObserver);
        initializeOwnedItems();
    }
    
    /**
     * If the database has not been initialized, we send a
     * RESTORE_TRANSACTIONS request to Android Market to get the list of purchased items
     * for this user. This happens if the application has just been installed
     * or the user wiped data. We do not want to do this on every startup, rather, we want to do
     * only when the database needs to be initialized.
     */
    private void restoreDatabase() {
        SharedPreferences prefs = getPreferences(MODE_PRIVATE);
        boolean initialized = prefs.getBoolean(DB_INITIALIZED, false);
        if (!initialized) {
            mBillingService.restoreTransactions();
            //Toast.makeText(this, R.string.restoring_transactions, Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * Creates a background thread that reads the database and initializes the
     * set of owned items.
     */
    private void initializeOwnedItems() {
        new Thread(new Runnable() {
            public void run() {
                doInitializeOwnedItems();
            }
        }).start();
    }

    /**
     * Reads the set of purchased items from the database in a background thread
     * and then adds those items to the set of owned items in the main UI
     * thread.
     */
    private void doInitializeOwnedItems() {
        Cursor cursor = mPurchaseDatabase.queryAllPurchasedItems();
        if (cursor == null) {
            return;
        }

        final Set<String> ownedItems = new HashSet<String>();
        try {
            int productIdCol = cursor.getColumnIndexOrThrow(
                    PurchaseDatabase.PURCHASED_PRODUCT_ID_COL);
            while (cursor.moveToNext()) {
                String productId = cursor.getString(productIdCol);
                ownedItems.add(productId);
            }
        } finally {
            cursor.close();
        }

        // We will add the set of owned items in a new Runnable that runs on
        // the UI thread so that we don't need to synchronize access to
        // mOwnedItems.
        mHandler.post(new Runnable() {
            public void run() {
                //mOwnedItems.addAll(ownedItems);
                //mCatalogAdapter.setOwnedItems(mOwnedItems);
            }
        });
    }

    /**
     * Called when this activity is no longer visible.
     */
    @Override
    protected void onStop() {
        super.onStop();
        ResponseHandler.unregister(mDungeonsPurchaseObserver);
    }
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.billing);
		
		mHandler = new Handler();
        mDungeonsPurchaseObserver = new DungeonsPurchaseObserver(mHandler);
        mBillingService = new BillingService();
        mBillingService.setContext(this);
        
        mPurchaseDatabase = new PurchaseDatabase(this);
		
		backButton = (Button) findViewById(R.id.back);
        backButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		bill = (Button) findViewById(R.id.buy);
		bill.setOnClickListener(this);
		
		
		checkType = 1;
		RadioGroup group = (RadioGroup) findViewById(R.id.billingGroup);
		group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				int id = group.getCheckedRadioButtonId();
				switch (id) {
				case R.id.billingBtn1:
					checkType = 1;
					break;
				case R.id.billingBtn2:
					checkType = 2;
					break;
				case R.id.billingBtn3:
					checkType = 3;
					break;
				case R.id.billingBtn4:
					checkType = 4;
					break;
				case R.id.billingBtn5:
					checkType = 5;
					break;
				default:
					break;
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.buy:
			if(!Utils.isConnect(Billing.this)) {
				com.WOWTradeNews.phone.Dialog.showDialog(Billing.this, "目前為無網路狀態");
				break;
			}
			if (Consts.DEBUG) {
                //Log.d(TAG, "buying: " + mItemName + " sku: " + mSku);
            }
			if (!mBillingService.checkBillingSupported()) {
	            System.out.println("DIALOG_CANNOT_CONNECT_ID");
	            showDialog(DIALOG_CANNOT_CONNECT_ID);
	        }
            //Toast.makeText(Billing.this, "aa", 0).show();
            if (!mBillingService.requestPurchase(/*"android.test.purchased"*/"c_001", mPayloadContents)) {
            	System.out.println("点击购买，buy buy");
                showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID);
            }
			break;

		default:
			break;
		}
	}
	
	
	/**
     * A {@link PurchaseObserver} is used to get callbacks when Android Market sends
     * messages to this application so that we can update the UI.
     */
    private class DungeonsPurchaseObserver extends PurchaseObserver {
        public DungeonsPurchaseObserver(Handler handler) {
            super(Billing.this, handler);
        }

        @Override
        public void onBillingSupported(boolean supported) {
            if (Consts.DEBUG) {
                Log.i(TAG, "supported: " + supported);
                System.out.println(" supported= " + supported);
            }
            if (supported) {
                restoreDatabase();
            } else {
                showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID);
                System.out.println("---onBillingSupported showDialog---");
            }
        }

        @Override
        public void onPurchaseStateChange(PurchaseState purchaseState, String itemId,
                int quantity, long purchaseTime, String developerPayload) {
            if (Consts.DEBUG) {
                Log.i(TAG, "onPurchaseStateChange() itemId: " + itemId + " " + purchaseState);
            }

            if (developerPayload == null) {
                //logProductActivity(itemId, purchaseState.toString());
            } else {
                //logProductActivity(itemId, purchaseState + "\n\t" + developerPayload);
            }

            if (purchaseState == PurchaseState.PURCHASED) {
                //mOwnedItems.add(itemId);
            }
            //mCatalogAdapter.setOwnedItems(mOwnedItems);
            //mOwnedItemsCursor.requery();
        }
        //**购买请求的回复*//*
        @Override
        public void onRequestPurchaseResponse(RequestPurchase request,
                ResponseCode responseCode) {
            if (Consts.DEBUG) {
            	System.out.println("onRequestPurchaseResponse:responseCode" + responseCode);
                Log.d(TAG, request.mProductId + ": " + responseCode);
            }
            if (responseCode == ResponseCode.RESULT_OK) {
                if (Consts.DEBUG) {
                    Log.i(TAG, "purchase was successfully sent to server");
                    //Toast.makeText(Billing.this, "purchase was successfully sent to server", 0).show();
                    SystemDBManager dbManager = new SystemDBManager(Billing.this);
                    dbManager.setMyCoin(dbManager.getMyCoin() + 10);
                    com.WOWTradeNews.phone.Dialog.showDialog(Billing.this, "購買成功,當前點數：" + dbManager.getMyCoin());
                    dbManager.closeDB();
                }
                //logProductActivity(request.mProductId, "sending purchase request");
            } else if (responseCode == ResponseCode.RESULT_USER_CANCELED) {
                if (Consts.DEBUG) {
                    Log.i(TAG, "user canceled purchase");
                }
                //logProductActivity(request.mProductId, "dismissed purchase dialog");
            } else {
                if (Consts.DEBUG) {
                    Log.i(TAG, "purchase failed");
                }
                //logProductActivity(request.mProductId, "request purchase returned " + responseCode);
            }
        }

        @Override
        public void onRestoreTransactionsResponse(RestoreTransactions request,
                ResponseCode responseCode) {
        	System.out.println("onRestoreTransactionsResponse:responseCode=" + responseCode);
            if (responseCode == ResponseCode.RESULT_OK) {
                if (Consts.DEBUG) {
                    Log.d(TAG, "completed RestoreTransactions request");
                }
                // Update the shared preferences so that we don't perform
                // a RestoreTransactions again.
                SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = prefs.edit();
                edit.putBoolean(DB_INITIALIZED, true);
                edit.commit();
            } else {
                if (Consts.DEBUG) {
                    Log.d(TAG, "RestoreTransactions error: " + responseCode);
                }
            }
        }
    }
	
}
